<template>
  <div class="app-container">
    <!-- 搜索模块 -->
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">

      <el-form-item label="是否批复" prop="isapprove">
        <el-select v-model="queryParams.isapprove" placeholder="是否批复" size="small" style="width: 240px">
          <el-option v-for="dict in isapproveOptions" :key="dict" :label="dict" :value="dict" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="批复时间" prop="scene">
            <el-date-picker
      v-model="queryParams.approvetime"
      type="date"
      placeholder="选择日期"
      format="yyyy.MM.dd">
    </el-date-picker>
      </el-form-item> -->
      <el-form-item label="年度" prop="year">
        <el-input v-model="queryParams.year" placeholder="年度" size="small" style="width: 240px"  />
      </el-form-item>
      <el-form-item label="井号" prop="wellname">
        <el-select v-model="queryParams.wellname" filterable placeholder="请选择">
          <el-option
            v-for="(item,index) in wellname"
            :key="index"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 图标权限模块 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-s-order" size="mini"
          @click="handleModel">模板下载
        </el-button>
        <el-button v-hasPermi="['admin:approve:form:add:post']" type="primary" plain icon="el-icon-upload" size="mini"
          @click="handleAdd">数据导入
        </el-button>
        <el-button v-hasPermi="['admin:approve:form:add:post']" type="primary" plain icon="el-icon-upload" size="mini"
          @click="handleAddPfh">批复号数据文件导入
        </el-button>
        <el-button v-hasPermi="['admin:approve:form:add:post']" type="primary" plain icon="el-icon-plus" size="mini"
          @click="handleAddData">数据录入
        </el-button>
        <el-button type="primary" plain icon="el-icon-download" size="mini"
          @click="handleDownload">数据下载
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['admin:approve:form:delete:{id}:delete']" type="danger" plain icon="el-icon-delete"
          size="mini" :disabled="multiple" @click="handleDelete">批量删除
        </el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>
    <!-- 展示模块 -->
    <el-table v-loading="loading" :data="approveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="isapprove" label="是否批复" align="center"> </el-table-column>
      <el-table-column prop="pfh" label="批复号" align="center" width="200" > </el-table-column>
      <el-table-column prop="approvetime" label="批复时间" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="starttime" label="开工时间" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="wellname" label="井号" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="welldepth" label="井深" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="cycle" label="周期" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="isdesign" label="有无设计" align="center"></el-table-column>
      <el-table-column prop="year" label="年度" align="center"></el-table-column>
      <el-table-column prop="batch" label="上报批次" align="center"></el-table-column>
      <el-table-column prop="type" label="类别" align="center"></el-table-column>
      <el-table-column prop="state" label="上报状态" align="center"></el-table-column>
      <!-- <el-table-column prop="product" label="生产上报" align="center"></el-table-column> -->
      <el-table-column prop="center" label="中心上报" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="zjtz" label="钻井投资" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="pfztz" label="批复总投资" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="pfzjtz" label="批复钻井投资" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="pfsytz" label="批复试油投资" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column
        v-if="hasPermi(['admin:approve:form:edit:post', 'system:clearsavefile:download:post', 'admin:budget:form:delete:{id}:delete'])"
        label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit"
            @click="lrForm=scope.row,addDataVisible=true,sjlrTitle='数据修改'">修改</el-button>
          <el-button v-hasPermi="['admin:approve:form:delete:{id}:delete']" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 文件上传|修改 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件导入" prop="path" v-if="this.form.id == undefined">
          <el-upload class="upload-demo" drag ref="uploadRef" :http-request="chunkUpload" :action="uploadUrl"
            :data="uploadData" :on-success="handleSuccess" :on-error="onError" name="file" :headers="headers"
            accept=".xlsx, .xls, .csv">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传xls/xlsx/csv文件，且列名不能重复</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="批复号文件导入" :visible.sync="pfhVisible" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="pfhForm" :model="pfhForm" :rules="rules" label-width="80px">
        <el-form-item label="文件导入" prop="path" v-if="this.pfhForm.id == undefined">
          <el-upload class="upload-demo" drag ref="uploadRef" :http-request="chunkUpload" :action="uploadUrl"
            :data="uploadData" :on-success="handleSuccess" :on-error="onError" name="file" :headers="headers"
            accept=".xlsx, .xls, .csv">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传xls/xlsx/csv文件，且列名不能重复</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addPfh">确 定</el-button>
        <el-button @click="pfhVisible=false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog @close="handleClose"  :title="sjlrTitle" :visible.sync="addDataVisible" width="1200px" append-to-body :close-on-click-modal="false">
      <el-form ref="lrForm" :inline="true" :model="lrForm" label-width="100px">
        <el-form-item label="是否批复" prop="isapprove">
          <el-select v-model="lrForm.isapprove" placeholder="是否批复" size="small" style="width: 240px">
            <el-option v-for="dict in isapproveOptions" :key="dict" :label="dict" :value="dict" />
          </el-select>
        </el-form-item>
        <el-form-item label="批复号" prop="isapprove">
          <el-input v-model="lrForm.pfh" placeholder="批复号" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="批复时间" prop="approvetime" >
          <el-date-picker v-model="lrForm.approvetime" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 240px"> </el-date-picker>
        </el-form-item>
        <el-form-item label="开工时间" prop="starttime">
          <el-date-picker v-model="lrForm.starttime" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 240px"> </el-date-picker>
        </el-form-item>
        <el-form-item label="井号" prop="wellname">
          <el-input v-model="lrForm.wellname" placeholder="井号" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="井类型" prop="welltype">
          <el-select v-model="lrForm.welltype" placeholder="井类型" size="small" style="width: 240px">
            <el-option key="试油" label="试油" value="试油" />
            <el-option key="探井" label="探井" value="探井" />
          </el-select>
        </el-form-item>
        <el-form-item label="井深" prop="welldepth">
          <el-input v-model="lrForm.welldepth" placeholder="井深" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="周期" prop="cycle">
          <el-input v-model="lrForm.cycle" placeholder="周期" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="有无设计" prop="isdesign">
          <el-select v-model="lrForm.isdesign" placeholder="有无设计" size="small" style="width: 240px">
            <el-option key="有" label="有" value="有" />
            <el-option key="无" label="无" value="无" />
          </el-select>
        </el-form-item>
        <el-form-item label="年度" prop="year">
          <el-input v-model="lrForm.year" placeholder="年度" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="上报批次" prop="batch">
          <el-input v-model="lrForm.batch" placeholder="上报批次" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="type">
          <el-input v-model="lrForm.type" placeholder="类别" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="上报状态" prop="state">
          <el-input v-model="lrForm.state" placeholder="上报状态" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="生产上报" prop="product">
          <el-date-picker v-model="lrForm.product" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 240px"> </el-date-picker>
        </el-form-item>
        <el-form-item label="中心上报" prop="center">
          <el-date-picker v-model="lrForm.center" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 240px"> </el-date-picker>
        </el-form-item>
        <el-form-item label="钻井投资" prop="zjtz">
          <el-input v-model="lrForm.zjtz" placeholder="钻井投资" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="层数" prop="layers">
          <el-input v-model="lrForm.layers" placeholder="层数" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="段数" prop="sections">
          <el-input v-model="lrForm.sections" placeholder="段数" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="批复总投资" prop="pfztz">
          <el-input v-model="lrForm.pfztz" placeholder="批复总投资" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="批复钻井投资" prop="pfzjtz">
          <el-input v-model="lrForm.pfzjtz" placeholder="批复钻井投资" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="批复试油投资" prop="pfsytz">
          <el-input v-model="lrForm.pfsytz" placeholder="批复试油投资" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="预警总投资" prop="yjztz">
          <el-input v-model="lrForm.yjztz" placeholder="预警总投资" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="预警钻井投资" prop="yjzjtz">
          <el-input v-model="lrForm.yjzjtz" placeholder="预警钻井投资" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="预警试油投资" prop="yjsytz">
          <el-input v-model="lrForm.yjsytz" placeholder="预警试油投资" style="width: 240px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addApproveClick">确 定</el-button>
        <el-button @click="addDataVisible=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listType, inspectHeaderAll, addType, addPfh, addApprove, editApprove, dataEche, editType, delType, downmodel } from "@/api/vadmin/budget/approve/approveapi";
import chunkUpload from '@/utils/chunkUpload'
import { getToken } from "@/utils/auth";
import { Decrypt } from "@/utils/AesHmacMD5";
import * as XLSX from 'xlsx';
import { getDictList } from "@/api/vadmin/budget/ledger/ledgerapi";
export default {
  name: "approve",
  data() {
    return {
      // 遮罩层
      loading: true,isapproveOptions:['待批复','已批复','取消上报'],pfhVisible:false,addDataVisible:false,
      lrForm:{isapprove:'已批复',pfh:'',approvetime:''},sjlrTitle:'数据录入',
      // 选中数组
      ids: [],
      valNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 批复表格数据
      approveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 场景数据字典
      sceneOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        isapprove:'已批复',
        pageNum: 1,  // 当前页数
        pageSize: 10,  // 每页显示几个
        wellname: '',
        year: '2024'
      },
      wellname:[], //井号
      // 表单参数
      form: {},pfhForm:{},
      // 表单校验
      rules: {
        // name: [
        //   { required: true, message: "模板名称不能为空", trigger: "blur" }
        // ],
        // scene: [
        //   { required: true, message: "使用场景不能为空", trigger: "blur" }
        // ],
        path: [
          { required: true, validator: this.validatorPath(), trigger: "blur" }
        ]
      },
      chunkUpload: chunkUpload, // 文件上传
      uploadUrl: process.env.VUE_APP_BASE_API + '/admin/system/upload_fileM/', //文件上传的路径
      uploadData: {},
      headers: {
        Authorization: "Bearer " + getToken()
      },
    };
  },
  created() {
    // 初始化模板列表
    this.getList();
    this.getDict();
    // 查询应用场景字典
    this.getDicts("explorate_type").then(response => {
      this.sceneOptions = response.data;
    });
  },
  methods: {
    //查询所有的区域 凹陷 井号
    getDict() {
      getDictList(this.addDateRange('aa')).then(response => {
        let res = JSON.parse(Decrypt(response.data));
        //井号数组
        this.wellname = res.wellname.flat();

      })
    },
    //弹窗关闭的回调--清空表单
    handleClose() {
      this.$refs.lrForm.resetFields();
    },
    validatorPath() {
      return (rule, value, callback) => {
        if (this.form.id == undefined && !value) {
          return callback(new Error("模板文件不能为空"));
        } else {
          callback();
        }
      }
    },
    /** 查询模板文件列表 */
    getList() {
      this.loading = true;
      listType(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        this.approveList = resData.results;
        this.total = resData.count;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        scene: undefined,
        path: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 文件上传按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "数据导入";
    },
    handleAddPfh(){
      this.pfhVisible = true;
    },
    handleAddData(){
      this.addDataVisible=true;
      this.lrForm.id=''
      this.sjlrTitle='数据录入'
    },
    handleModel(){
      var data = [['序号','井号','有无设计','年度','上报批次','类别','上报状态','生产上报','中心上报','是否批复','批复时间','开工时间','井深','周期','钻井投资','层数','段数','试油投资','批复总投资','批复钻井投资','批复试油投资']]
      //添加到work sheel中
      const ws = XLSX.utils.aoa_to_sheet(data)
      //创建新的work book
      const wb = XLSX.utils.book_new()
      //讲work shell添加到work book中并命名为‘Shell1’
      XLSX.utils.book_append_sheet(wb,ws,'Sheet1')
      //将work book写入文件，并取名为new_excel.xlsx
      XLSX.writeFile(wb,'批复模板.xlsx')
      // downmodel({fileName:'批复模板.xlsx'}).then(response => {
      //   debugger
      //     var files = JSON.parse(Decrypt(response.data))
      //     this.download(files.path, files.name);

      //   });
    },
    handleDownload(){
      var fileName = "项目投资库.csv"; //使用当前时间戳作为文件名
      var columnDelimiter = ","; //列分割符
      var lineDelimiter = "\r\n"; //行分割符
      var keyValue_=['序号','井号','有无设计','年度','上报批次','类别','上报状态','生产上报','中心上报','是否批复','批复时间','开工时间','井深','周期','钻井投资','层数','段数','试油投资','批复总投资','批复钻井投资','批复试油投资']
      var keyValue=['xh','wellname','isdesign','year','batch','type','state','product','center','isapprove','approvetime','starttime','welldepth','cycle','zjtz','layers','sections','sytz','pfztz','pfzjtz','pfsytz']
      let result = ""; // 最终结果的字符串
      for(var i=0;i<keyValue_.length;i++){
        result +=this.transferred(keyValue_[i]) +columnDelimiter;
      }
      result += lineDelimiter;
      for (var i = 0; i < this.approveList.length; i++) {
        for(var j=0;j<keyValue.length;j++){
          if (keyValue[j]=='xh'){
            result +=this.transferred(i+'') +columnDelimiter;
          }else{
            result +=this.transferred(this.approveList[i][keyValue[j]]==undefined ? '': this.approveList[i][keyValue[j]]+'') +columnDelimiter;
          }
        }
        result += lineDelimiter;
      }
      this.downCsvFile(fileName,result)
    },
    transferred(data) {
      return data.replace(/<br>/g, "\r\n").replace(/&gt;/g, ">");
    },
    downCsvFile(fileName, result) {
      var fileName = fileName; //使用当前时间戳作为文件名
      var blob = new Blob(["\uFEFF" + result], { type: "text/csv;" }); //记得将编码格式设置一下，避免最终下载的文件出现乱码
      var downloadLink = document.createElement("a");
      if ("download" in downloadLink) {
        var url = URL.createObjectURL(blob);
        downloadLink.href = url;
        downloadLink.download = fileName;
        downloadLink.hidden = true;
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      } else {
        if (navigator.msSaveBlob) {
          //IE10+
          navigator.msSaveBlob(blob, fileName);
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$refs.uploadRef.clearFiles()
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this, this.form.id == undefined) {
            addType(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.open = false;
              this.getList();
            });
          } else {
            editType(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.open = false;
              this.getList();
            })
          }
        }
      });
    },
    addPfh(){
      addPfh(this.pfhForm).then(response => {
        this.msgSuccess(response.msg);
        this.pfhVisible = false;
        this.getList();
      });
    },
    addApproveClick(){
      if(this.lrForm.id==''){
        addApprove(this.lrForm).then(response => {
          this.msgSuccess(response.msg);
          this.addDataVisible = false;
          this.getList();
        });
      }else{
        editApprove(this.lrForm).then(response => {
          this.msgSuccess(response.msg);
          this.addDataVisible = false;
          this.getList();
        })
      }

    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.valNames = selection.map(item => item.formCode);
      this.single = selection.length !== 1;
      this.multiple = selection.length < 2;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var ids=[]
      if(row.id!=undefined){
        ids = [row.id]
      }else{
         ids = this.ids;
      }
      const names = row.name || this.valNames
      this.$confirm('是否确认删除该数据项? 请谨慎操作！', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delType({id:ids});
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      });
    },
    // 场景字典翻译
    sceneFormat(row, column) {
      return this.selectDictLabel(this.sceneOptions, row.scene);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // const id = row.id || this.ids;
      dataEche({ "id": row.id }).then((response) => {
        this.form = JSON.parse(Decrypt(response.data));
        this.open = true;
        this.title = "模板修改";
      });
    },
    /** 文件上传成功调用的钩子函数 */
    handleSuccess(data) {
      this.form.path = data.saveFile
      this.pfhForm.path = data.saveFile
      this.$message.success('文件上传成功！');
      // inspectHeaderAll({ 'path': data.saveFile }).then(response => {
      //   var resData = JSON.parse(Decrypt(response.data))
      //   if (resData.bol) {
      //     this.form.path = data.saveFile
      //     this.$message.success('文件上传成功！');
      //     this.$refs.uploadRef.clearFiles()
      //   } else {
      //     this.onInspect(resData.repeat_values)
      //   }
      // })

    },
    /** 文件上传失败调用的钩子函数 */
    onError() {
      this.form.path = undefined
      this.$message.error('文件上传失败！');
      this.$refs.uploadRef.clearFiles()
    },
    /** 重复列回显函数 */
    onInspect(data) {
      this.form.path = undefined
      this.$message.error('文件' + data + '列重复，请检查之后重新上传！');
      this.$refs.uploadRef.clearFiles()
    }
  }
};
</script>
     <style scoped>
::v-deep .el-table th.el-table__cell > .cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
    white-space: nowrap !important;
}

  </style>
